package com.czkt.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.czkt.config.CustomRealm;
import com.czkt.pojo.SysRight;
import com.czkt.pojo.SysUser;
import com.czkt.pojo.vo.SysUserVo;
import com.czkt.service.ISysRightService;
import com.czkt.service.ISysRoleService;
import com.czkt.service.SysUserService;
import com.czkt.utils.MD5Utils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.cache.CacheManagerAware;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Controller
public class UserController {

    @Autowired
    SysUserService sysUserService;


    @Autowired
    ISysRoleService sysRoleService;

    @Autowired
    ISysRightService sysRightService;




    @Resource
    StringRedisTemplate stringRedisTemplate;




    @RequestMapping("/doLogin")
    public Object doLogin(String usrName, String usrPassword, Boolean remeberMe, Model model, HttpSession session) {


        String errStr = stringRedisTemplate.opsForValue().get(usrName + "errorCount:");
        System.out.println(errStr);

        //获取用户错误的次数
        Integer errCount =errStr!=null? Integer.parseInt(errStr):1;
        if (errCount > 5) {
            model.addAttribute("message", "密码错误次数过多，请24小时后再试");
            return "login";
        }

//        Md5Hash hash = new Md5Hash(usrPassword,"czkt",2);
        //根据用户名和密码创建凭证
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(usrName, usrPassword,remeberMe!=null);


        System.out.println("httpSession"+session.getId());

        try {

           Subject subject= SecurityUtils.getSubject();
            //通过subject将token交给securityManager  如果认证通过则返回认证对象，否则抛出异常
            subject.login(usernamePasswordToken);


            //获取认证通过的对象
            SysUserVo sysUser= (SysUserVo)subject.getPrincipal();

            System.out.println("会话："+subject.getSession().getId());

            //获取用户拥有的权限
            List<SysRight> roleRightList= sysRightService.getListByRoleId(sysUser.getUsrRoleId());

            sysUser.getRole().setRights(roleRightList);

            //将认证通过的对象放到session中
            session.setAttribute("loginUser", sysUser);
        } catch (UnknownAccountException e) {
            model.addAttribute("message", "账号不存在！");
            return "login";
        }catch (LockedAccountException e){
            model.addAttribute("message", "账号被禁用！");
            return "login";
        }catch (AuthenticationException e){
            //每次密码错误；错误次数+1
            stringRedisTemplate.opsForValue().increment(usrName + "errorCount:",1);
            stringRedisTemplate.expire(usrName + "errorCount:",24, TimeUnit.HOURS);
            model.addAttribute("message", "账号或密码错误！");
            return "login";
        }


        //登录成功则清理错误次数
        stringRedisTemplate.delete(usrName + "errorCount:");
//
//        DefaultWebSecurityManager defaultWebSecurityManager = (DefaultWebSecurityManager) SecurityUtils.getSecurityManager();
//        Collection<Realm> realms= defaultWebSecurityManager.getRealms();
//        if ( realms != null && !realms.isEmpty()) {
//            Iterator var3 = realms.iterator();
//            while(var3.hasNext()) {
//                Realm realm = (Realm)var3.next();
//                if (realm instanceof CustomRealm) {
//                    CustomRealm tempReaml= (CustomRealm) realm;
//                    tempReaml.clearMyCachedAuthorizationInfo();
//                }
//            }
//        }



        return "main";


    }

    @RequestMapping("/logout")
    public Object logout(HttpSession session) {
        session.removeAttribute("loginUser");
//        SecurityUtils.getSubject().logout();
        return "login";
    }


    @RequestMapping("/user/list")
    public Object getList(@RequestParam(defaultValue = "1") Integer pageIndex,
                          @RequestParam(defaultValue = "2") Integer pageSize,
                          @RequestParam(defaultValue = "0") Long roleId,
                          SysUserVo sysUserVo,

                          Model model) {
        IPage<SysUserVo> page = new Page<SysUserVo>(pageIndex, pageSize);
        sysUserVo.setUsrRoleId(roleId);
//        SysUserVo sysUserVo = new SysUserVo();
        model.addAttribute("userPager", sysUserService.getPage(page, sysUserVo));
        model.addAttribute("roles", sysRoleService.list());
        model.addAttribute("usrName", sysUserVo.getUsrName());
        model.addAttribute("roleId", sysUserVo.getUsrRoleId());


        return "user/list";
    }

    @RequestMapping("/user/list1")
    public Object getList1(@RequestParam(defaultValue = "1") Integer pageIndex,
                          @RequestParam(defaultValue = "2") Integer pageSize,
                          @RequestParam(defaultValue = "0") Long roleId,
                          SysUserVo sysUserVo,

                          Model model) {
        IPage<SysUserVo> page = new Page<SysUserVo>(pageIndex, pageSize);
        sysUserVo.setUsrRoleId(roleId);
//        SysUserVo sysUserVo = new SysUserVo();
        model.addAttribute("userPager", sysUserService.getPage(page, sysUserVo));
        model.addAttribute("roles", sysRoleService.list());
        model.addAttribute("usrName", sysUserVo.getUsrName());
        model.addAttribute("roleId", sysUserVo.getUsrRoleId());


        return "user/list";
    }

    @GetMapping("/list")
    @ResponseBody
    public Object index() {
        return sysUserService.list();
    }


    /**
     * 定义跳转到新增页的方法
     */
    @RequestMapping("/user/add")
    public Object toAdd(Model model) {
        model.addAttribute("roles", sysRoleService.list());
        return "user/add";
    }


    /**
     * 保存用户信息的方法
     */
    @PostMapping("/user/save")
    public Object saveUser(SysUser sysUser) {
        //获取加密后的字符串
        String md5Pwd=MD5Utils.getMd5String(sysUser.getUsrPassword(),"czkt",2);

        sysUser.setUsrPassword(md5Pwd);
        boolean result = sysUserService.saveOrUpdate(sysUser);
        if (result) {
            return "redirect:/user/list";
        } else if (sysUser.getUsrId() == 0) {
            return "redirect:/user/add";
        } else {
            return "redirect:/user/edit?usrId=" + sysUser.getUsrId();
        }
    }


    /**
     * 获取用户详细并跳转修改页面
     */
    @RequestMapping("/user/edit")
    public Object toUpdate(long usrId, Model model) {

        model.addAttribute("user", sysUserService.getById(usrId));
        model.addAttribute("roles", sysRoleService.list());
        return "user/edit";
    }


    /**
     * 删除用户信息
     */
    @RequestMapping("/crm/user/del/{usrId}")
    @ResponseBody
    public Object del(@PathVariable() long usrId, Model model) {
        Map resultMap = new HashMap();
        resultMap.put("delResult", sysUserService.removeById(usrId));
        return resultMap;
    }


}
